package com.saint.tvtest.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.saint.tvtest.R;
import com.saint.tvtest.Utils.AppUtils;
import com.saint.tvtest.Utils.HttpUtil;
import com.saint.tvtest.adapter.MenuAdapter;
import com.saint.tvtest.bean.CatContent;
import com.saint.tvtest.bean.CatsBean;
import com.saint.tvtest.bean.DataBean;
import com.saint.tvtest.bean.MainBean;
import com.saint.tvtest.bean.SubCatsBean;
import com.saint.tvtest.view.MyTextView;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Main2Activity extends Activity {
    private Activity act;
    private ImageView ivMianBg, ivSubBg;
    private MyTextView tvTitle;
    private ListView listViewMenu;
    private ListView listViewSubmenu;
    //    String mainBg = "file:///android_asset/bg.jpg";
    private BitmapDrawable bitmapDrawable;
    private Callback<String> mainCallBack, catsCallBcak, subCatsCallBack;
    private Toast toast;
    public static String url;
    private MainBean.DataBean mainBean;
    private CatsBean catsBean;
    private SubCatsBean subCatsBean;
    private CatContent catContent;
    private MenuAdapter menuAdapter, submenuAdapter;
    private MediaPlayer mediaPlayer;
    public static AssetFileDescriptor fd;
    private RelativeLayout rlParent;
    public static final int HANDLER_GET_SUB_DATA = 1;
    public static final int HANDLER_GET_SUB_CONTENT = 2;
    private TextView tvExit;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_GET_SUB_DATA:
                    getSubCats(catsBean.getData().get(msg.arg1).getId() + "");
                    break;
                case HANDLER_GET_SUB_CONTENT:
                    Log.e("SUBCONTENT", "data : " + subCatsBean.getData() + "   size: " + subCatsBean.getData().size());
                    if (null == subCatsBean.getData() || subCatsBean.getData().size() == 0) {
                        tShort("选择时间点无新闻");
                    } else {
                        Intent intent = new Intent(act, Main3Activity.class);
                        intent.putExtra("title", subCatsBean.getData().get(msg.arg1).getName());
                        intent.putExtra("cat_id", subCatsBean.getData().get(msg.arg1).getId() + "");
                        startActivity(intent);
                    }
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        act = this;
        initView();
        initCallBack();
        initData();
    }

    private void initView() {
        rlParent = findViewById(R.id.rl_parent);
        ivMianBg = findViewById(R.id.iv_main_bg);
        tvTitle = findViewById(R.id.tv_title);
        listViewMenu = findViewById(R.id.list_view_menu);
        listViewSubmenu = findViewById(R.id.list_view_submenu);
        listViewMenu.setItemsCanFocus(true);
        listViewSubmenu.setItemsCanFocus(true);
        ivSubBg = findViewById(R.id.iv_sub_bg);
        tvExit = findViewById(R.id.tv_exit);
        tvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initData() {
//        bitmapDrawable = new BitmapDrawable(mainBg);
        try {
            fd = act.getAssets().openFd("favorite.wav");
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = AppUtils.readAssetsTextReturnStr(this, "ip");
//        Glide.with(act).load(mainBg).into(ivMianBg);
//        listViewMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                setDataToSubTitle(mainBean.getCats().get(i).getChildren());

//            }
//        });

//        listViewMenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                getSubCats(catsBean.getData().get(i).getId() + "");
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//
//            }
//        });

//        StateListDrawable drawable = new StateListDrawable();
//        drawable.addState(new int[]{android.R.attr.state_focused}, bitmapDrawable);
//        listViewMenu.setSelector(drawable);
//        listViewSubmenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                getSubCatContent(subCatsBean.getData().get(i).getId() + "");
//                if (null == subCatsBean.getData() || subCatsBean.getData().size() == 0) {
//                    tShort("选择时间点无新闻");
//                    return;
//                }
//                Intent intent = new Intent(act, Main3Activity.class);
//                intent.putExtra("title", subCatsBean.getData().get(i).getName());
//                intent.putExtra("cat_id", subCatsBean.getData().get(i).getId() + "");
//                startActivity(intent);
//            }
//        });

        getData();
    }


    private void initCallBack() {
        mainCallBack = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful() && null != response.body()) {
                    mainBean = new Gson().fromJson(response.body(), MainBean.class).getData();
                    if (!TextUtils.isEmpty(mainBean.getCat_bg())) {
                        Glide.with(act)
                                .load(mainBean.getCat_bg())
                                .placeholder(bitmapDrawable)
                                .error(bitmapDrawable)
                                .into(ivMianBg);
                        tvTitle.setText(mainBean.getCat_desc());
//                        setDataToView();
                    }
                } else {
                    onFailure(call, new Throwable("response body is null"));
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                tShort("加载失败：" + t.getMessage());
                Log.e("LOADINGData", t.getMessage());
            }
        };

        catsCallBcak = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful() && null != response.body()) {
                    catsBean = new Gson().fromJson(response.body(), CatsBean.class);
                    setDataToView();

                } else {
                    onFailure(call, new Throwable("response body is null"));
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                tShort("加载失败：" + t.getMessage());
                Log.e("LOADINGData", t.getMessage());
            }
        };

        subCatsCallBack = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful() && null != response.body()) {
                    subCatsBean = new Gson().fromJson(response.body(), SubCatsBean.class);
                    Log.e("Main2Act", "二级栏目数据： " + response.body());
                    setDataToSubTitle(subCatsBean.getData());
                } else {
                    onFailure(call, new Throwable("response body is null"));
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                tShort("加载失败：" + t.getMessage());
                Log.e("LOADINGData", t.getMessage());
            }
        };


    }

    private void getData() {
        Call<String> mainCall = HttpUtil.getInstance(url).requestMainBean();
        mainCall.enqueue(mainCallBack);

        Call<String> catsCall = HttpUtil.getInstance(url).getCats();
        catsCall.enqueue(catsCallBcak);

    }

    private void getSubCats(String catId) {
        Map<String, String> map = new ArrayMap<>();
        map.put("cat_id", catId);

        Call<String> subCatsCall = HttpUtil.getInstance(url).getSubCats(map);
        subCatsCall.enqueue(subCatsCallBack);
    }


    private void setDataToView() {

        menuAdapter = new MenuAdapter(catsBean.getData(), act, handler, 1);
        listViewMenu.setAdapter(menuAdapter);
    }

    private void setDataToSubTitle(List<DataBean> children) {
        submenuAdapter = new MenuAdapter(children, act, handler, 2);
        listViewSubmenu.setAdapter(submenuAdapter);
    }


    public void tShort(String msg) {
        if (null == toast) {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setText(msg);
        }

        toast.show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        play();
        return super.onKeyDown(keyCode, event);
    }


    private void play() {
        try {
            //播放 assets/a2.mp3 音乐文件
//            if (null == mediaPlayer) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            mediaPlayer.prepare();
//            } else {
//                mediaPlayer.start();
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        tvTitle.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        super.onStart();
    }

    @Override
    protected void onStop() {
        tvTitle.setEllipsize(null);
        super.onStop();
    }


}
